<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="微信用户id" prop="wxUserId" label-width="88px">
        <el-input
          v-model="queryParams.wxUserId"
          placeholder="请输入微信用户id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="对话id" prop="dialogueId">
        <el-input
          v-model="queryParams.dialogueId"
          placeholder="请输入对话id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select v-model="queryParams.role" placeholder="请选择角色" clearable>
          <el-option
            v-for="dict in dict.type.ai_chat_role"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.ai_chat_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户类型" prop="userType">
        <el-select v-model="queryParams.userType" placeholder="请选择用户类型" clearable>
          <el-option
            v-for="dict in dict.type.user_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['ai:chat:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['ai:chat:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['ai:chat:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ai:chat:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="chatList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="聊天id" align="center" prop="chatId" v-if="true"/>
      <el-table-column label="微信用户id" align="center" prop="wxUserId" />
      <el-table-column label="对话id" align="center" prop="dialogueId" />
      <el-table-column label="角色" align="center" prop="role">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ai_chat_role" :value="scope.row.role"/>
        </template>
      </el-table-column>
      <el-table-column label="内容" align="center" prop="content" >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.role!=='user'"
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="openDetailDialog(scope.row.content)"
          >查看回答
          </el-button>
          <span  v-text="scope.row.content"
                 v-if="scope.row.role==='user'"></span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ai_chat_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="用户类型" align="center" prop="userType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.user_type" :value="scope.row.userType"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" />

<!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--        <template slot-scope="scope">-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['ai:chat:edit']"-->
<!--          >修改</el-button>-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['ai:chat:remove']"-->
<!--          >删除</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改聊天记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="微信用户id" prop="wxUserId">
          <el-input v-model="form.wxUserId" placeholder="请输入微信用户id" />
        </el-form-item>
        <el-form-item label="对话id" prop="dialogueId">
          <el-input v-model="form.dialogueId" placeholder="请输入对话id" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option
              v-for="dict in dict.type.ai_chat_role"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in dict.type.ai_chat_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--详情 -->
    <el-dialog @open="handleOpen" title="内容" :visible.sync="openDetail" width="800px" append-to-body>
      <div class="content-view-mode">
        <el-radio-group v-model="viewMode" size="small" @change="handleViewModeChange">
          <el-radio-button label="previewOnly">预览模式</el-radio-button>
          <el-radio-button label="edit&preview">编辑模式</el-radio-button>
        </el-radio-group>
      </div>
        <CherryMarkdown ref="cherry" :defaultModel="viewMode"></CherryMarkdown>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDetail"> 关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listChat, getChat, delChat, addChat, updateChat } from "@/api/ai/chat";
import CherryMarkdown from '@/components/CherryMarkdown/index';

export default {
  name: "Chat",
  dicts: ['ai_chat_role', 'ai_chat_status','user_type'],
  components: {
    CherryMarkdown
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 聊天记录表格数据
      chatList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        wxUserId: undefined,
        dialogueId: undefined,
        role: undefined,
        status: undefined,
      },
      // 详情加载
      loadingDetail: false,
      // 打开详情
      openDetail: false,
      // 表单参数
      form: {},
      showContent: '',
      // 表单校验
      rules: {
        chatId: [
          { required: true, message: "聊天id不能为空", trigger: "blur" }
        ],
        wxUserId: [
          { required: true, message: "微信用户id不能为空", trigger: "blur" }
        ],
        dialogueId: [
          { required: true, message: "对话id不能为空", trigger: "blur" }
        ],
        role: [
          { required: true, message: "角色不能为空", trigger: "change" }
        ],
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
      },
      viewMode: 'previewOnly'
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.$nextTick(()=>{
      console.log(this.$refs) // 输出实例
    })
  },
  watch: {
    viewMode(newVal) {
      // 确保当 viewMode 变化时，CherryMarkdown 组件能够同步更新
      if (this.$refs.cherry && this.$refs.cherry.isInit()) {
        this.$refs.cherry.switchModel(newVal);
      }
    }
  },
  methods: {
    /** 查询聊天记录列表 */
    getList() {
      this.loading = true;
      listChat(this.queryParams).then(response => {
        this.chatList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        chatId: undefined,
        wxUserId: undefined,
        dialogueId: undefined,
        role: undefined,
        content: undefined,
        status: undefined,
        delFlag: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.chatId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加聊天记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const chatId = row.chatId || this.ids
      getChat(chatId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改聊天记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.chatId != null) {
            updateChat(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addChat(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const chatIds = row.chatId || this.ids;
      this.$modal.confirm('是否确认删除聊天记录编号为"' + chatIds + '"的数据项？').then(() => {
        this.loading = true;
        return delChat(chatIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ai/chat/export', {
        ...this.queryParams
      }, `chat_${new Date().getTime()}.xlsx`)
    },
    // 打开信息详情
    openDetailDialog(content) {
      this.openDetail = true;
      this.showContent = content;
      this.viewMode = 'previewOnly'; // 默认预览模式
    },
    // 取消按钮
    closeDetail() {
      this.openDetail = false;
      this.showContent = '';
    },
    handleOpen() {
      this.$nextTick(() => {
        const cherry = this.$refs.cherry;
        console.log(cherry);
        cherry.setMarkdown(this.showContent);
        // 确保初始化完成后设置正确的模式
        setTimeout(() => {
          if (cherry && cherry.isInit()) {
            cherry.switchModel(this.viewMode);
          }
        }, 100);
      });
    },
    handleViewModeChange() {
       console.log(this.viewMode)
       // 需要调用 CherryMarkdown 的切换模式功能
       if (this.$refs.cherry) {
         this.$refs.cherry.switchModel(this.viewMode);
       }
    }
  }
};
</script>

<style scoped>
.content-view-mode {
  margin-bottom: 15px;
  text-align: right;
}
</style>
